<template>
  <div class="user-views">
    <el-card class="user-views-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>个人资料</span>
          <el-button
            @click="router.push({ name: 'accountChangePassword' })"
            type="info"
            v-blur
            plain
            >修改密码
          </el-button>
        </div>
      </template>
      <!-- 个人资料表单 -->
      <div class="user-profile">
        <el-form
          :model="state.form"
          :rules="rules"
          :label-position="'top'"
          ref="formRef"
          @keyup.enter="onSubmit(formRef)"
        >
          <el-form-item class="upload" porp="avatar">
            <el-upload
              v-model:file-list="fileList"
              :headers="config"
              list-type="picture-card"
              :limit="1"
              name="avatarfile"
              :on-change="changeAvaterImg"
              :on-remove="handleRemove"
              :auto-upload="false"
            >
              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="用户名" prop="userName">
            <el-input v-model="state.form.userName" :disabled="true" />
          </el-form-item>
          <el-form-item label="用户昵称" prop="nickName">
            <el-input v-model="state.form.nickName" />
          </el-form-item>
          <!-- <FormItem label="手机号" type="number" v-model="state.form.mobile" placeholder="手机号" prop="mobile" /> -->
          <el-form-item label="手机" prop="phonenumber">
            <el-input
              v-model="state.form.phonenumber"
              placeholder="请输入手机号码"
            >
              <!-- <template #append>
                <el-button type="primary">{{
                  state.form.phonenumber ? "点击修改" : "绑定"
                }}</el-button>
              </template> -->
            </el-input>
          </el-form-item>
          <FormItem
            label="性别"
            v-model="state.form.sex"
            type="radio"
            :data="{
              content: { 0: '男', 1: '女' },
              childrenAttr: { border: true },
            }"
          />
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="state.form.email" placeholder="请输入电子邮箱">
              <!-- <template #append>
                <el-button type="primary">{{
                  state.form.email ? "点击修改" : "绑定"
                }}</el-button>
              </template> -->
            </el-input>
          </el-form-item>
          <!-- 按钮组 -->
          <el-form-item class="submit-buttons">
            <!-- <el-button @click="onResetForm(formRef)">重置</el-button> -->
            <el-button
              type="primary"
              :loading="state.formSubmitLoading"
              @click="onSubmit(formRef)"
              >保存
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <!-- 预览图展示区域 -->
    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, onMounted, toRaw } from "vue";
import { useRouter } from "vue-router";
import { useUserInfo } from "@/store/userInfo"; //用户信息仓库
import { ElNotification } from "element-plus"; //处理导航信息
import { _upload } from "@/utils/axios";
import type {
  FormInstance,
  FormRules,
  UploadFile,
  UploadProps,
  UploadUserFile,
  UploadFiles,
} from "element-plus"; //form类型
import { Plus } from "@element-plus/icons-vue";

const router = useRouter();
const formRef = ref<FormInstance>();
const userInfo = useUserInfo();

const state: { formSubmitLoading: boolean; form: any; host: any } = reactive({
  formSubmitLoading: false,
  form: userInfo.$state, //整个userInfo的state数据
  host: "",
});

const rules = reactive<FormRules>({
  phonenumber: [
    {
      required: true,
      message: "请输入联系方式",
      trigger: "blur",
    },
    {
      validator: function (rule, value, callback) {
        if (/^1[34578]\d{9}$/.test(value) == false) {
          callback(new Error("手机号格式错误"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  email: [
    {
      required: true,
      message: "请输入邮箱",
      trigger: "blur",
    },
    {
      validator: function (rule, value, callback) {
        if (
          /^\w{1,64}@[a-z0-9\-]{1,256}(\.[a-z]{2,6}){1,2}$/i.test(value) ==
          false
        ) {
          callback(new Error("邮箱格式错误"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
});
const config = {
  Authorization: JSON.parse(localStorage.getItem("adminInfo") as any)?.token,
};
const fileList = ref<UploadUserFile[]>([
  {
    name: "avatar.jpeg",
    url: state.form.avatar,
  },
]);
// 头像照片
const realUploadFile = ref<UploadUserFile[]>([]);
//重置表单事件
// const onResetForm = (formEl: FormInstance | undefined) => {};
//提交表单事件
const onSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) {
      //修改个人资料
      userInfo.changeUserProfile(state.form);
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 预览图绑定数据
const dialogImageUrl = ref("");
const dialogVisible = ref(false);

//上传头像
const changeAvaterImg: UploadProps["onChange"] = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log("文件限制", uploadFile, uploadFiles);
  const { uid, name, size } = uploadFile;
  //   文件类型限制
  const fileTypeFlag = /^.doc|.docx|.xlsx|.pdf|.jpg|.jpeg|.png$/.test(
    name.substring(name.lastIndexOf(".")).toLowerCase()
  );
  if (!fileTypeFlag) {
    ElNotification({
      type: "warning",
      message: "文件类型只能是.doc|.docx|.xlsx|.pdf|.jpg|.jpeg|.png",
    });
    const selectFileList = fileList.value.filter((item) => {
      return item.uid != uid;
    });
    fileList.value = selectFileList;
    return;
  }
  //文件大小进行校验
  if ((size as number) > 1024 * 1024 * 5) {
    ElNotification({
      type: "warning",
      message: "文件大小不能超过5Mb",
    });
    const selectFileList = fileList.value.filter((item) => {
      return item.uid != uid;
    });
    fileList.value = selectFileList;
    return;
  }
  // 将上传营业执照存入列表
  fileList.value.push(uploadFile);
  realUploadFile.value = [];
  let formData = new FormData();
  formData.append("avatarfile", uploadFile.raw as any); //添加文件对象
  // formData.append("name", "pdf"); //添加文件对象
  _upload("/system/user/profile/avatar", formData, "").then((res: any) => {
    state.form.avatar =
      state.host === "" ? res.data.url : state.host + res.data.fileName;
    console.log("上传头像", state.form);
  });
};
//移除图片
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};
// 预览图片
// const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
//   dialogImageUrl.value = uploadFile.url!;
//   dialogVisible.value = true;
// };
onMounted(() => {
  console.log("用户数据", userInfo.$state);
  //获取个人头像资料
});
</script>
<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-profile {
  width: 360px;
  max-width: 100%;
}

.submit-buttons :deep(.el-form-item__content) {
  justify-content: flex-end;
}

// :deep(.el-form-item__content) {
//     justify-content: flex-end;
// }

:deep(.el-upload-list--picture-card) {
  --el-upload-list-picture-card-size: 100px;
}

:deep(.el-upload--picture-card) {
  --el-upload-picture-card-size: 100px;
}
</style>
